package com.xk857.system.controller.pub;

import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.base.Captcha;
import com.xk857.system.req.RegisterREQ;
import com.xk857.system.service.ISysUserService;
import com.xk857.util.base.Result;
import com.xk857.util.redis.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author CV大魔王
 * @Description 用户信息-公开接口
 * @date 2021/2/26 11:55
 */
@Api(value = "用户管理(公开)", tags = "用户管理接口(公开)")
@RestController
@RequestMapping("/pub/user")
public class PubSysUserController {


    @Autowired
    private ISysUserService sysUserService;


    @Autowired
    private RedisService redisService;

    @ApiImplicitParam(name = "username", value = "用户名", required = true)
    @ApiOperation("校验用户名是否存在")
    @GetMapping("/username/{username}")
    public Boolean checkUsername(@PathVariable("username") String username) {
        return sysUserService.checkUsername(username);
    }


    @ApiOperation("用户注册接口")
    @PostMapping("/register")
    public Result register(@RequestBody RegisterREQ req) {
        return sysUserService.register(req);
    }

    @ApiImplicitParam(name = "phone", value = "手机号码", required = true)
    @ApiOperation("发送注册验证码")
    @GetMapping("/registe/code/{phone}")
    public Result getRegisterCode(@PathVariable String phone) {
        return sysUserService.sendMsg(phone);
    }


    @ApiImplicitParam(name = "phone", value = "手机号码", required = true)
    @ApiOperation("发送更改密码验证码")
    @GetMapping("/pwd/code/{phone}")
    public Result getChangePwdCode(@PathVariable String phone) {
        return sysUserService.sendMsgChangePwd(phone);
    }


    @ApiOperation("更改密码")
    @PostMapping("/change/pwd")
    public Result changePassword(@RequestBody RegisterREQ req) {
        return sysUserService.changePassword(req);
    }


    @ApiOperation("获登录取验证码")
    @GetMapping("/code")
    public Result getCode() {
        // 算术类型
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        captcha.getArithmeticString();  // 获取运算的公式：4-9+1=?
        String text = captcha.text();   // 获取运算的结果：-4
        String uuid = UUID.randomUUID().toString();
        redisService.set(uuid,text,180); // 设置过期时间，3分钟
        // 封装验证码信息
        Map<String, Object> imgResult = new HashMap<String, Object>(2) {{
            put("img", captcha.toBase64());
            put("uuid", uuid);
        }};
        return Result.ok(imgResult);
    }
}
